﻿using LeRenard.Libraries.PlatformInspection.InfoNodes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;

namespace LeRenard.Libraries.PlatformInspection.Inspectors.Network
{
    public class ConnectivityNetworkInspectorModule : InspectorModule<NetworkInspector>
    {
        /// <summary>
        /// Constructions
        /// </summary>
        public ConnectivityNetworkInspectorModule() 
            : base("Connectivity") 
        { 
        }

        /// <summary>
        /// Gets the information this module gathers.
        /// </summary>        
        protected override IEnumerable<InfoNode> GetInformationImpl()
        {
            var infoNodes = new List<InfoNode>();            

            var connectionStatus = NetworkInterface.GetIsNetworkAvailable();

            infoNodes.Add(new InfoNode(
                "Network Availibility",
                value: connectionStatus ? "Available" : "Not available",
                displayStrategy: InfoNodeEmptyValueDisplayStrategy.TreatAsNormalInfoNode
            ));

            infoNodes.Add(new InfoNode(
                "Internet Availibility ('www.google.com')",
                value: GetIsInternetConnectionAvailable("http://www.google.com") ? "Available" : "Not available",
                displayStrategy: InfoNodeEmptyValueDisplayStrategy.TreatAsNormalInfoNode
            )); 

            return infoNodes.OrderBy(inf => inf.Name);
        }

        /// <summary>
        /// Determines whether one can connect to a specific host.
        /// </summary>
        /// <returns></returns>
        private bool GetIsInternetConnectionAvailable(string host)
        {
            try
            {
                using (var client = new WebClient())
                {
                    using (var stream = client.OpenRead(host))
                        return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
